//
//  LinnerViewController.m
//  LINNER
//
//  Created by wei wang on 2017/4/17.
//  Copyright © 2017年 weiwang. All rights reserved.
//

#import "LinnerViewController.h"
#import "LinnerSetViewController.h"
@interface LinnerViewController ()<UITableViewDelegate,UITableViewDataSource>{
    
    dispatch_source_t timer;
}

@property(nonatomic) uint32_t totalBytesRead;

@property (weak, nonatomic) IBOutlet UILabel *batteryValue;


@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *modeBtn;

@property (weak, nonatomic) IBOutlet UIImageView *modeImage;
/** 文字数组 **/
@property(nonatomic,strong) NSArray *titleArray;
/** imageArray **/
@property(nonatomic,strong) NSArray *imageArray;

@property(nonatomic,strong) NSArray *voiceArray;


@property (weak, nonatomic) IBOutlet UIView *maskView;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

/** SetheadsetEQ **/
@property(nonatomic,strong) NSArray *headsetEQ;

@property (weak, nonatomic) IBOutlet UIButton *voiceBtn;

@property (weak, nonatomic) IBOutlet UIView *batteryView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *batteryNSLayout;

/** voiceData **/
@property(nonatomic,strong) NSArray *voiceDataArray;

@end

@implementation LinnerViewController
- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    // watch for received data from the accessory

    _totalBytesRead = 0;

    [self setNavigationStyle];
    [self getLinnerStatus];
  
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
       [self getBattery];

    });
    
    
}

- (void)getBattery{
    
    /* 开启一个定时器 查询电量*/
    NSLog(@"定时器开启");
    timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_queue_create("1", DISPATCH_QUEUE_CONCURRENT));
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 60 * NSEC_PER_SEC, 5 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        
        NSString *sendata = @"aa000302";
        const char *buf = [sendata UTF8String];
        NSMutableData *data = [NSMutableData data];
        if (buf)
        {
            uint32_t len = (uint32_t)strlen(buf);
            
            char singleNumberString[3] = {'\0', '\0', '\0'};
            uint32_t singleNumber = 0;
            for(uint32_t i = 0 ; i < len; i+=2)
            {
                if ( ((i+1) < len) && isxdigit(buf[i]) && (isxdigit(buf[i+1])) )
                {
                    singleNumberString[0] = buf[i];
                    singleNumberString[1] = buf[i + 1];
                    sscanf(singleNumberString, "%x", &singleNumber);
                    uint8_t tmp = (uint8_t)(singleNumber & 0x000000FF);
                    [data appendBytes:(void *)(&tmp) length:1];
                }
                else
                {
                    break;
                }
            }
            
            NSLog(@"发送%@",data);
           [[EADSessionController sharedController] writeData:data];
        }
        
        
    });
    dispatch_resume(timer);

    
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    if(timer){
        dispatch_source_cancel(timer);
        timer = nil;
    }
    NSLog(@"定时器取消");

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.imageArray = @[@"bg_equilibrium",@"bg_bass",@"bg_voice",@"bg_treble"];
    self.titleArray = @[@"均衡模式",@"低音增强",@"人声增强",@"高音增强"];
    self.voiceArray = @[@"降噪",@"监听",@"关闭"];
    self.voiceDataArray = @[@"aa01022c01",@"aa01022c02",@"aa01022c00"];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(EQback) name:GetHEADSETEQ object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(headsetVoice) name:GetHEADSETVOICE object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(BATTERY) name:GetHEADSETBATTERY object:nil];

    self.maskView.backgroundColor = [[UIColor colorWithHexString:@"B1B1B1"] colorWithAlphaComponent:0.4f];
    
}
/** 电池电量  **/
- (void)BATTERY{
    
    NSLog(@"%.1f",20*((double)[AppDelegate globalDelegate].GetheadsetBattery/100));
    
    self.batteryValue.text = [NSString stringWithFormat:@"%.f%%",(double)[AppDelegate globalDelegate].GetheadsetBattery];
    
    self.batteryNSLayout.constant = 20-20*((double)[AppDelegate globalDelegate].GetheadsetBattery/100) + 4;
    
}

/** 获取耳机模式 **/
- (void)EQback{
    
    
    UIButton *selectBtn = self.modeBtn[[AppDelegate globalDelegate].GetheadsetEQ];
    [self checkStauts:selectBtn];

    
}

/** 获得耳机降噪/监听状态 **/
- (void)headsetVoice{
    
    [self.voiceBtn setTitle:MyNSLocalizedString(self.voiceArray[[AppDelegate globalDelegate].GetheadsetVoice]) forState:UIControlStateNormal];
    NSLog(@"%@",self.voiceArray[[AppDelegate globalDelegate].GetheadsetVoice]);
}

- (void)setNavigationStyle{
    
    [self setNavigationBarTitle:MyNSLocalizedString(@"默")];
    [self setLeftButtonImage:[UIImage imageNamed:@"tittle_back_nor"]];
    [self.navigationController.navigationBar makeTransparent_nornav];
    [self setRightButtonImage:[UIImage imageNamed:@"icon_set"]];
    
}

- (void)getLinnerStatus{
    /*获取耳机eq状态*/
    NSString *sendata = @"aa000294";
    const char *buf = [sendata UTF8String];
    [self sendata:buf];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        /*获得耳机降噪／监听状态*/
        NSString *sendata = @"aa0002ac";
        const char *buf = [sendata UTF8String];
        [self sendata:buf];
        
    });
    
}

- (void)onRightButtonClick:(id)sender{
    
    LinnerSetViewController *vc = [LinnerSetViewController new];
    [self.navigationController pushViewController:vc animated:YES];
    
}


- (IBAction)hidemaskView:(id)sender {
    
    self.maskView.hidden = YES;
}

- (IBAction)changeVoiceMode:(id)sender {
    
    self.maskView.hidden = NO;
}

- (void)checkStauts:(UIButton *)sender{
    
    for (UIButton *btn in _modeBtn) {
        
        btn.selected = NO;
    }
    
    UIButton *Btn = (UIButton *)[self.view viewWithTag:sender.tag];
    
    self.modeImage.image = [UIImage imageNamed:self.imageArray[sender.tag-1]];
    Btn.selected = YES;
    
}

- (IBAction)changeMode:(UIButton *)sender {
    
    for (UIButton *btn in _modeBtn) {
        
        btn.selected = NO;
    }
    
    
    NSInteger number = sender.tag - 1;
    const char *buf = [self.headsetEQ[number] UTF8String];

    [self sendata:buf];
    
    UIButton *Btn = (UIButton *)[self.view viewWithTag:sender.tag];
    
    self.modeImage.image = [UIImage imageNamed:self.imageArray[sender.tag-1]];
    Btn.selected = YES;
    [Btn setTitle:MyNSLocalizedString(self.titleArray[number]) forState:UIControlStateNormal];

}

- (void)sendata:(const char*)buf{
    
    NSMutableData *data = [NSMutableData data];
    if (buf)
    {
        uint32_t len = (uint32_t)strlen(buf);
        
        char singleNumberString[3] = {'\0', '\0', '\0'};
        uint32_t singleNumber = 0;
        for(uint32_t i = 0 ; i < len; i+=2)
        {
            if ( ((i+1) < len) && isxdigit(buf[i]) && (isxdigit(buf[i+1])) )
            {
                singleNumberString[0] = buf[i];
                singleNumberString[1] = buf[i + 1];
                sscanf(singleNumberString, "%x", &singleNumber);
                uint8_t tmp = (uint8_t)(singleNumber & 0x000000FF);
                [data appendBytes:(void *)(&tmp) length:1];
            }
            else
            {
                break;
            }
        }
        NSLog(@"综合发送%@",data);

        [[EADSessionController sharedController] writeData:data];
    }

}

- (NSArray *)headsetEQ{
    
    if (!_headsetEQ) {
        
        _headsetEQ = @[@"aa01021400",@"aa01021401",@"aa01021402",@"aa01021403"];
    }
    return _headsetEQ;
}

#pragma mark - --------------------------UITableView dataSource--------------------------

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.voiceArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
        cell.textLabel.textColor = [UIColor colorWithHexString:@"#00B293"];
        [cell.textLabel setFont:[UIFont systemFontOfSize:15.f]];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.text = MyNSLocalizedString(self.voiceArray[indexPath.row]);
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 33;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
    
}
#pragma mark - --------------------------UITableView delegate--------------------------

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    self.maskView.hidden = YES;
    //降噪模式
    NSString *senddata = self.voiceDataArray[indexPath.row];
    const char *buf = [senddata UTF8String];
    [self sendata:buf];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
